import express from "express";
import {
  addToBase,
  getAll,
  deleteById,
  tableExists,
  getSortData,
  getSortByAge
} from "./database";
import { join, resolve, isAbsolute } from "path";

const PORT = 4000;
const app = express();

app.use(express.static("public"));
app.use(express.json());

app.get("/get_cats", async (req, res) => {
  const data = await getAll();
  if (data) {
    res.status(200);
    res.json(data[0]);
  } else {
    console.error("Error getting cat from database");
    res.status(500).end("Failed to get data from database");
  }
});

app.get("/sort_cats", (req, res) => {
  const { breed, age, size } = req.query;
  getSortData(breed, Number(age), Number(size))
    .then((data) => {
      res.status(200);
      res.json(data[0]);
    })
    .catch((err: Error) => {
      console.error(err.message);
      res.status(404).end(err.message);
    });
});

app.get("/sort_age" , (req , res) => {
  const sort = req.query.sort;
  getSortByAge(Number(sort)).then(data => {
    res.status(200);
    res.json(data[0])
  }).catch((err : Error)=> {
    console.error(err.message);
    res.status(404).end(err.message)
  })
})

app.get("/img/add.png", (req, res) => {
  const path = join(resolve(""), req.url);
  if (isAbsolute(path)) res.status(200).sendFile(path);
  else res.status(404).end();
});


app.post("/add_cat", (req, res) => {
  const { breed, imageurl, age } = req.body;
  addToBase(breed, imageurl, age)
    .then(() => {
      res.status(200).end("Cat added to the database");
    })
    .catch((err) => {
      console.error("Error adding cat to the database: " + err);
      res.status(500).end("Failed to add data to the database");
    });
});

app.delete("/delete_cat", (req, res) => {
  const id:number = req.body.id;
  deleteById(id)
    .then(() => {
      res.status(200).end("Сat has been removed from the database");
    })
    .catch((err) => {
      console.error("Error remove cat from the database: " + err);
      res.status(500).end("Failed to delete data from the database");
    });
});

app.listen(PORT, () => {
  console.log(`http://localhost:${PORT}`);
  tableExists();
});
